Arrays


An array is a type of variable that allows for more than one piece of data to be stored under the same name. You can think of it as several pieces of information stored in a column (see below). The array is an array of numbers

array_of_numbers.jpg
Notice that the index begins at 0! This is important because it makes arrays easy to use with loops.

Think back to the simple addition calculator we did earlier. If we wanted to add 10 numbers we would need to declare 10 variables! An array needs to be declared once.

Adding multiple Numbers

We will use an array to add 10 numbers together. First an array will need to be declared.

int [] numbers = new int [10];
int Added = 0;
 
This array is of integers and has a length of 10, this means it can hold 10 elements.

Next we create a loop to populate, or enter, the numbers.

for (int i = 0; i < 10; i++)
{
    numbers[i]= Int32.Parse(System.Console.ReadLine());
}
The Int32.Parse() converts the string to an integer.

After the numbers have been entered it is time to add them all up. We will use a loop to do that too.

for (int i = 0; i < 10; i++)
{
    Added = Added + numbers[i];
}
The loop above adds the next number on each time time around, or iteration.

Now, the only thing left to do is display the results.

System.Console.WriteLine("= " + Added);
System.Console.ReadLine();

The final code looks like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Add
{
    class Program
    {
        static void Main(string[] args)
        {
            int [] numbers = new int [10];
            int Added = 0;
            System.Console.WriteLine("Enter each number followed by the return key, requires ten numbers");
 
            for (int i = 0; i < 10; i++)
            {
                numbers[i]= Int32.Parse(System.Console.ReadLine());
            }
 
            for (int i = 0; i < 10; i++)
            {
                Added = Added + numbers[i];
            }
 
            System.Console.WriteLine("= " + Added);
            System.Console.ReadLine();
        }
    }
}
 

2-dimensional arrays

It is also important to note that an array can have more than 1 dimension as it was above. See example below.

2d_array.jpg

You can think of this as a minesweeper type of game where the user would input a "coordinate" and the computer would return a hit or miss. "1" would equal hit "0" would equal miss.

User input: mines[1,1]
Output: miss

User input: mines[0,1]
Output: hit

Another example of a 2d array would be a deck of cards where one row would hold the suit and the other would hold the number of the card.

2d_array_cards.jpg

Arrays can be very useful in programming.